package com.keelau.ui.fx;


import com.keelau.utils.ValidateTools;
import com.sun.javafx.scene.control.skin.LabeledText;
import com.teamdev.jxbrowser.chromium.*;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;
import com.teamdev.jxbrowser.chromium.javafx.BrowserView;
import javafx.application.Platform;
import javafx.event.*;
import javafx.event.Event;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.awt.*;
import java.util.ArrayList;

public class AliDetailCrawlerUI extends AnchorPane  {


    Logger logger = LoggerFactory.getLogger(this.getClass());
    TextField urlTextField;

    Button btnBrowser;

    Button btnCrawler;

    TabPane tabPane ;

    static ArrayList<Browser> browserList = new ArrayList<Browser>();


    public AliDetailCrawlerUI(){

        BorderPane borderPane = new BorderPane();
        AnchorPane.setRightAnchor(borderPane,0.0);
        AnchorPane.setLeftAnchor(borderPane,0.0);
        AnchorPane.setTopAnchor(borderPane,0.0);
        AnchorPane.setBottomAnchor(borderPane,0.0);
        VBox vBox = new VBox();

        //add toobar
        //ToolBar toolBar = new ToolBar();
        //
        ToolBar toolBar = new ToolBar();

        AnchorPane anchorPane = new AnchorPane();
        urlTextField = new TextField("");
        urlTextField.setPrefHeight(29.0);
        urlTextField.setPadding(new Insets(0,5,0,0));
        urlTextField.setAlignment(Pos.CENTER_LEFT);

        AnchorPane.setLeftAnchor(urlTextField,0.0);
        AnchorPane.setRightAnchor(urlTextField,200.0);

        HBox hBox = new HBox();
        btnBrowser= new Button();
        btnBrowser.setText("浏览");

        btnCrawler = new Button();
        btnCrawler.setText("抓取商品");

        hBox.setSpacing(5);
        AnchorPane.setRightAnchor(hBox,5.0);
        hBox.getChildren().addAll(btnBrowser,btnCrawler);

        anchorPane.getChildren().addAll(urlTextField,hBox);
       // anchorPane.setBorder(ComponentUtils.getBorder(null));

       // toolBar.setBorder(ComponentUtils.getBorder(Color.color(1,0,0)));
       // toolBar.getItems().addAll(new BorderPane(anchorPane));

        vBox.setFillWidth(true);
        vBox.getChildren().add(anchorPane);
        //and tool bar
        borderPane.setTop(vBox);


        //add tab
        tabPane = new TabPane();

        Tab dataTab = new Tab("数据列表");

        AliProductTableUI dataTable = new AliProductTableUI();

        dataTab.setContent(dataTable);

        tabPane.getTabs().add(dataTab);

        borderPane.setCenter(tabPane);
        getChildren().add(borderPane);

        tabPane.getTabs().get(0).setClosable(false);
        addListenter();
    }

    public void addListenter(){
        urlTextField.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {
                if(event.getCode() == KeyCode.ENTER ){
                    btnBrowser.fire();
                }
            }
        });

        btnBrowser.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                if(ValidateTools.isUrl(urlTextField.getText())) {
                    createBrowserTab(urlTextField.getText(), null);
                    tabPane.getSelectionModel().select(tabPane.getTabs().size()-1);
                }
                else{
                    Alert alert = new Alert(Alert.AlertType.ERROR,"非法URL");
                    alert.show();
                }
            }
        });

    }

    public void createBrowserTab(String url,Browser mybrowser){
        tabPane.getTabs().add(getTabContent(url,mybrowser));
        if(tabPane.getTabs().size()>1 && tabPane.getTabs().get(1).isClosable()) {
            tabPane.getTabs().get(1).setClosable(false);
        }
    }

    public Tab getTabContent(String url,Browser mybrowser){
        Tab tab = new Tab();
        tab.setText("正在打开………");

        if(mybrowser==null)
            mybrowser = new Browser();
        BrowserView browserView = new BrowserView(mybrowser);

        final Browser browser = mybrowser;
        StackPane stackPane = new StackPane();
        stackPane.getChildren().add(browserView);
        tab.setContent(stackPane);
        mybrowser.setContextMenuHandler(new BrowserContextMenu(stackPane,this));

        browser.addLoadListener(new LoadAdapter() {
            @Override
            public void onFinishLoadingFrame(FinishLoadingEvent event) {
                super.onFinishLoadingFrame(event);
                if(event.isMainFrame()) {
                    String title = browser.getTitle();
                    if (title.length() > 15) title = title.substring(15);
                    final String tabText = title;
                    Platform.runLater(() -> {
                        tab.setText(tabText);
                    });
                }

            }
        });
        browser.setPopupHandler(new PopupHandler() {
            public PopupContainer handlePopup(PopupParams params) {
                return new PopupContainer() {
                    public void insertBrowser(final Browser browser, final Rectangle initialBounds) {
                        Platform.runLater(()-> {
                                tabPane.getTabs().add(getTabContent(null,browser));
                                tabPane.getSelectionModel().select(tabPane.getTabs().size()-1);
                        });
                    }
                };
            }
        });
        if(url!=null && !url.isEmpty())
            browser.loadURL(url);

        tab.setOnCloseRequest(new EventHandler<Event>() {
            @Override
            public void handle(Event event) {

                int index = tabPane.getSelectionModel().getSelectedIndex();
                logger.info("tab setOnCloseRequest");
                logger.info("tab select index:" + index);
                browser.dispose();
                if(browserList.size()>index)
                browserList.remove(index);

            }
        });

        tabPane.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                EventTarget eventTarget = event.getTarget();
                boolean isTabClick = (eventTarget.getClass() == LabeledText.class);
                if(isTabClick && event.getClickCount()==2 ) {
                    logger.info(" tab pane mouse double click");
                    int index = tabPane.getSelectionModel().getSelectedIndex();
                    logger.info("tab setOnCloseRequest");
                    logger.info("tab select index:" + index);
                    browser.dispose();
                    browserList.remove(index);
                    tabPane.getTabs().remove(index);
                }
            }
        });

        browserList.add(browser);

        return  tab;
    }


    public void doCrawler(){

    }



}
